package com.zhengtoon.mctoon.conv.service.sdzc;

import com.zhengtoon.mctoon.conv.bean.sdzc.*;
import com.zhengtoon.mctoon.conv.bean.ws.BaseLetter;
import com.zhengtoon.mctoon.conv.bean.ws.NotAcceptLetter;
import com.zhengtoon.mctoon.conv.dao.sdzc.LetterMapper;
import com.zhengtoon.mctoon.conv.dao.sdzc.ReplyAttachmentMapper;
import com.zhengtoon.mctoon.conv.dao.sdzc.ReplyMapper;
import com.zhengtoon.mctoon.conv.dao.sdzc.TransferLetterMapper;
import com.zhengtoon.mctoon.conv.service.sdzc.SendLetterMessageJobService;
import com.zhengtoon.mctoon.conv.service.sdzc.ZfhfSystemService;
import com.zhengtoon.mctoon.conv.utils.AppConstant;
import com.zhengtoon.mctoon.conv.utils.SysConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * 同步首都之窗数据
 *
 * @author 刘振华
 * @version 2017-06-27
 */
@Service
public class SendLetterMessageJobServiceImpl implements SendLetterMessageJobService {
    private static Logger log = LoggerFactory.getLogger(LetterServiceImpl.class);

    @Autowired
    private LetterMapper letterMapper;

    @Autowired
    private TransferLetterMapper transferLetterMapper;

    @Autowired
    private ReplyMapper replyMapper;

    @Autowired
    private ReplyAttachmentMapper replyAttachmentMapper;

    @Autowired
    private ZfhfSystemService zfhfService;  // 中科软系统服务

    /**
     * 信件有回复时发送提醒通知 144637
     *
     * @return
     */
    @Override
    public boolean syncLetterMessage() {
        // 1. 调用中科软查询信件列表接口
        BaseLetter baseLetter = zfhfService.getCommunityLetterList();
        if (baseLetter == null) {
            log.info("本次未抓取到所有信件列表");
            return false;
        }
        // 2. 同步不受理信件列表
        syncNotAcceptLetterList(baseLetter.getNotAcceptLetterList());
        // 3. 同步办理信件列表
        syncFinishedLetterList(baseLetter.getFinishedLetterList());
        return false;
    }

    /**
     * 同步已完成信件  144637
     *
     * @param letterList
     * @return
     */
    private boolean syncFinishedLetterList(List<Letter> letterList) {
        // TODO 重构
        if (CollectionUtils.isEmpty(letterList)) {
            log.info("本次未抓取到信件列表");
            return true;
        }
        String sysLetterIdTemp = "";
        for (Letter letter : letterList) {
            try {
                // 2. 更新信件表
                if ("".equals(sysLetterIdTemp) || !letter.getSysLetterId().equals(sysLetterIdTemp)) {
                    Letter letterEntity = new Letter();
                    letterEntity.setLetterId(letter.getLetterId());
                    letterEntity.setSysLetterId(letter.getSysLetterId());
                    letterEntity.setSubmitTime(letter.getSubmitTime());
                    letterEntity.setLetterStatus(letter.getLetterStatus());
                    letterEntity.setUpdateTime(new Date().getTime());
                    letterMapper.updateLetter(letterEntity);
                }
                sysLetterIdTemp = letter.getSysLetterId();
                // 3. 更新转办信件表
                // 查询是否存在
                Integer transIdCount = transferLetterMapper.queryTransIdCount(letter.getTransferLetterId());
                if (transIdCount == 0) {
                    TransferLetter transferLetterEntity = new TransferLetter();
                    transferLetterEntity.setSysLetterId(letter.getSysLetterId());
                    transferLetterEntity.setTransferLetterId(letter.getTransferLetterId());
                    transferLetterEntity.setCreateTime(new Date().getTime());
                    transferLetterEntity.setUpdateTime(new Date().getTime());
                    transferLetterMapper.insertTransferLetter(transferLetterEntity);
                }
                // 4. 调用中科软查询信件结果接口
                List<Reply> replyList = zfhfService.getCommunityLetterReply(letter.getLetterId());
                if (CollectionUtils.isEmpty(replyList)) {
                    log.info("本次未抓取到信件回复列表");
                    return true;
                }

                int replyCount = 0;
                int notOpenCount = 0;
                for (Reply reply : replyList) {
                    // 5. 更新回复表
                    // 查询该回复是否已存在
                    Integer replyIdCount = replyMapper.queryReplyIdCount(reply.getReplyId());
                    if (replyIdCount == 0) {
                        reply.setSysLetterId(letter.getSysLetterId());
                        reply.setCreateTime(new Date().getTime());
                        reply.setUpdateTime(new Date().getTime());
                        replyMapper.insertReply(reply);
                        replyCount++;
                        // 如果有修改为不公开的 记录
                        if (0 == reply.getOpenFlag()) {
                            notOpenCount++;
                        }
                    }
                    // 判断是否存在附件
                    List<ReplyAttachment> replyAttachmentList = reply.getAttachmentList();
                    if (CollectionUtils.isEmpty(replyAttachmentList)) {
                        log.info("本次未抓取到信件回复中的附件");
                        continue;
                    }
                    for (ReplyAttachment replyAttach : replyAttachmentList) {
                        try {
                            // 查询该回复附件是否已存在
                            Integer attachIdCount = replyAttachmentMapper.queryAttachIdCount(replyAttach.getReplyAttachId());
                            if (attachIdCount == 0) {
                                replyAttach.setCreateTime(new Date().getTime());
                                replyAttach.setUpdateTime(new Date().getTime());
                                replyAttachmentMapper.insertReplyAttachment(replyAttach);
                            }
                        } catch (Exception e) {
                            log.error("获取附件失败", e);
                            continue;
                        }
                    }
                }
                if (replyCount > 0) {
                    if (notOpenCount > 0) {
                        letterMapper.updateOpenTypeBySysLetterId(letter.getSysLetterId());
                    }
                    // 8 更新信件状态为已回复 bjtStatus
                    letterMapper.updateBjtStatusBySysLetterId(letter.getSysLetterId());
                }
            } catch (Exception e) {
                log.error("同步受理信件异常", e);
                continue;
            }
        }
        return true;
    }

    /**
     * 同步不受理信件  144637
     *
     * @param notAcceptLetterList notAcceptLetterList
     */
    private boolean syncNotAcceptLetterList(List<NotAcceptLetter> notAcceptLetterList) {
        if (CollectionUtils.isEmpty(notAcceptLetterList)) {
            log.info("本次无不受理信件..");
            return true;
        }
        for (NotAcceptLetter letter : notAcceptLetterList) {
            try {
                Letter letterEntity = new Letter();
                letterEntity.setLetterId(letter.getLetterId());
                letterEntity.setSysLetterId(letter.getSysLetterId());
                letterEntity.setSubmitTime(letter.getSubmitTime());
                letterEntity.setUpdateTime(new Date().getTime());
                letterEntity.setBjtStatus(AppConstant.NOT_ACCEPT_LETTER_BJT_STATUS);
                letterMapper.updateNotAcceptLetter(letterEntity);
            } catch (Exception e) {
                log.error("同步不受理信件异常", e);
                continue;
            }
        }
        return true;
    }

}